﻿#include "PluginEngine.h"
#include <QDebug>

EAEngine::PluginEngine::PluginEngine()
{
    plugins = new QVector<IPluginObject*>();
}

EAEngine::PluginEngine::~PluginEngine()
{
    if(plugins)
    {
        foreach (IPluginObject* plugin, plugins->toList())
        {
            if(plugin)
            {
                delete plugin;
                plugin=0;
            }
        }
        delete plugins;
        plugins=0;
    }
}

QVector<EAEngine::IPluginObject*>* EAEngine::PluginEngine::GetPlugins()
{
    if(plugins->isEmpty())//只允许加载一次
    {
        QDir pluginsDir = QDir(QDir::currentPath()+"/Plugins");
        foreach(QString filename, pluginsDir.entryList(QDir::Files))
        {
            QPluginLoader* pluginLoader = new QPluginLoader();
            pluginLoader->setFileName(pluginsDir.absolutePath()+"/"+filename);
            if(pluginLoader->load())
            {
                QObject* object = pluginLoader->instance();
                IPluginObject* plugin = qobject_cast<IPluginObject*>(object);
                if(plugin)
                {
                    qDebug()<<"Load plugin " << plugin->GetPluginUid()<<" success!";
                    plugins->push_back(plugin);
                }
            }
            delete pluginLoader;
        }
    }
    return plugins;
}

QObject* GetInstance()
{
    EAEngine::PluginEngine* instance = new EAEngine::PluginEngine();
    QObject* object = qobject_cast<QObject*>(instance);
    return object;//需要使用智能指针接收返回值，或手动delete返回值，才能析构object.
}
